/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.modules.admin.controller;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import lombok.AllArgsConstructor;

import javax.validation.Valid;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springblade.common.utils.PoiExcelUtil;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.admin.vo.brand.BrandVersionUploadResultVo;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestParam;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springblade.modules.admin.entity.BuildingExt;
import org.springblade.modules.admin.vo.BuildingExtVO;
import org.springblade.modules.admin.wrapper.BuildingExtWrapper;
import org.springblade.modules.admin.service.IBuildingExtService;
import org.springblade.core.boot.ctrl.BladeController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 楼盘信息 控制器
 *
 * @author ysq
 * @since 2023-08-29
 */
@RestController
@AllArgsConstructor
@RequestMapping("admin/building/ext")
@Api(value = "楼盘信息", tags = "楼盘信息接口")
public class BuildingExtController extends BladeController {

	private final IBuildingExtService buildingExtService;

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入buildingExt")
	public R<BuildingExtVO> detail(BuildingExt buildingExt) {
		BuildingExt detail = buildingExtService.getOne(Condition.getQueryWrapper(buildingExt));
		return R.data(BuildingExtWrapper.build().entityVO(detail));
	}

	/**
	 * 分页 楼盘信息
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入buildingExt")
	public R<IPage<BuildingExtVO>> list(BuildingExt buildingExt, Query query) {
		IPage<BuildingExt> pages = buildingExtService.page(Condition.getPage(query), Condition.getQueryWrapper(buildingExt));
		return R.data(BuildingExtWrapper.build().pageVO(pages));
	}


	/**
	 * 自定义分页 楼盘信息
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入buildingExt")
	public R<IPage<BuildingExtVO>> page(BuildingExtVO buildingExt, Query query) {
		IPage<BuildingExtVO> pages = buildingExtService.selectBuildingExtPage(Condition.getPage(query), buildingExt);
		return R.data(pages);
	}

	/**
	 * 新增 楼盘信息
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入buildingExt")
	public R save(@Valid @RequestBody BuildingExt buildingExt) {
		return R.status(buildingExtService.save(buildingExt));
	}

	/**
	 * 修改 楼盘信息
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入buildingExt")
	public R update(@Valid @RequestBody BuildingExt buildingExt) {
		return R.status(buildingExtService.updateById(buildingExt));
	}

	/**
	 * 新增或修改 楼盘信息
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入buildingExt")
	public R submit(@Valid @RequestBody BuildingExt buildingExt) {
		return R.status(buildingExtService.saveOrUpdate(buildingExt));
	}


	/**
	 * 删除 楼盘信息
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "逻辑删除", notes = "传入ids")
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		return R.status(buildingExtService.deleteLogic(Func.toLongList(ids)));
	}


	/**
	 * 删除 楼盘信息
	 */
	@PostMapping("/upload/excel")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "上传Excel", notes = "传入ids")
	public R uploadExcel(@RequestParam("file") MultipartFile file) throws IOException {
		List<BuildingExt> list = buildingExtService.list();
		Map<Long, List<BuildingExt>> map = list.stream().collect(Collectors.groupingBy(BuildingExt::getBuildingId));
		List<BuildingExt> updateList = new ArrayList<>(16);
		Workbook wb = null;
		try {
			wb = WorkbookFactory.create(file.getInputStream());
		} catch (InvalidFormatException e) {
			return R.fail("请使用正确的模板导入");
		}
		List<Map<String, Object>> readAll = PoiExcelUtil.readExcel(wb, 0, 0, 2, 0);
		List<Long> buildingIds = new ArrayList<>(16);
		for (int i = 0; i < readAll.size(); i++) {
			Map<String, Object> objectMap = readAll.get(i);
			Long buildingId = Convert.toLong(objectMap.get("项目ID"));
			final String buildingToTime = Convert.toStr(objectMap.get("项目要求到达时长"), "");
			if (StrUtil.isNotEmpty(buildingToTime)) {
				String time = buildingToTime + "m";
				List<BuildingExt> buildingExts = map.get(buildingId);
				if (buildingExts != null && buildingExts.size() > 0) {
					BuildingExt buildingExt = buildingExts.get(0);
					buildingExt.setMalfunctionWorkArrivalTime(time);
					updateList.add(buildingExt);
				} else {
					buildingIds.add(buildingId);
				}
			}
		}
		if (updateList.size() > 0) {
			List<List<BuildingExt>> partitions = Lists.partition(updateList, 20);
			for (List<BuildingExt> li : partitions) {
				buildingExtService.updateBatchById(li);
			}
		}
		return R.data("数据总共" + (readAll.size() - 1) + "条处理成功=" + updateList.size() + "条异常id=" + JSON.toJSONString(buildingIds));
	}

}
